package com.grm.demo.cyclicbarrier;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.CyclicBarrier;

public class MyCyclicBarrier implements Runnable {
    private CyclicBarrier barrier;
    private String name;

    public MyCyclicBarrier(CyclicBarrier barrier, String name) {
        this.barrier = barrier;
        this.name = name;
    }

    @Override
    public void run() {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
            System.out.println(sdf.format(new Date()) + " " + name + "出发去饭店");
            Random random = new Random();
            Thread.sleep((long)(random.nextDouble() * 10000) + 1000);
            System.out.println(sdf.format(new Date()) + " " + name + "到了饭店");

            barrier.await();
            System.out.println(sdf.format(new Date()) + " " + name + "开始吃饭");
            Thread.sleep((long)(random.nextDouble() * 10000) + 1000);
            System.out.println(sdf.format(new Date()) + " " + name + "吃完了");

            //重用CyclicBarrier
            barrier.await();
            System.out.println(sdf.format(new Date()) + " " + name + "离开餐厅");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
